// app.js

import { 
  getLonginCode,
  codeToToken,
  checkToken,
  checkSession } 
from './service/login-api'
import{ TOKEN_KEY } from './constants/token-const'

App({ 
     // 监听小程序的初始化.
  onLaunch :function(options) {
     //获取设备的信息
      const res =  wx.getSystemInfoSync()
      this.globalData.screenWidth = res.screenWidth //屏幕宽度
      this.globalData.screenHeight = res.screenHeight //屏幕高度
      this.globalData.statusBarHeight = res.statusBarHeight //状态栏高度
      this.globalData.aspectRatio = this.globalData.screenHeight / this.globalData.screenWidth  //屏幕的宽高比

      //登录
      this.loginLogic()
  },
  loginLogic: async function(){
 // 登录之前要判断token是否过期，是否存在token，判断session_key是否过期

 const token = wx.getStorageSync('TOKEN_KEY')
 //  因为如果token过期或者没有传token，在或者传错token都会有报错码
  const checkResult = await checkToken()
  console.log(checkResult);
  const isCheckSession = await checkSession()

  if(!token || checkResult.errorCode || !isCheckSession){
  //登录 
  this.userLogin()     
  }
  }, 
  userLogin: async function(){
    // 1.从小程序中拿到临时的code
   const code = await getLonginCode()
    // console.log(code);

    //2.将code发送给服务器
    const tokenResult = await codeToToken(code)
    const token = tokenResult.token
    //保存到storage里面
    wx.setStorageSync('TOKEN_KEY', token)
  },
  globalData: {
    screenWidth: 0,
    screenHeight:0,
    statusBarHeight:0,
    navBarHeight:44,
    aspectRatio:0
  }
})
